package com.yzt.message.custom;

import android.os.Parcel;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yzt.zhuju.rongyun.IMMessageType;

import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;

import io.rong.common.ParcelUtils;
import io.rong.imlib.MessageTag;
import io.rong.imlib.model.MessageContent;

@MessageTag(value = IMMessageType.TYPE_CHAT_ROOM_MSG ,flag = MessageTag.ISPERSISTED| MessageTag.ISCOUNTED)
public class ChatRoomMessageContent extends MessageContent {
    private int type;
    private String data;

    @Override
    public byte[] encode() {
        JSONObject object =new JSONObject();
        object.put("type",type);
        object.put("data",data);
        return object.toString().getBytes(StandardCharsets.UTF_8);

    }

    public ChatRoomMessageContent() {
    }

    public ChatRoomMessageContent(byte[] data) {
        super(data);
        String jsonStr=null;
        try {
            jsonStr =new String(data, StandardCharsets.UTF_8);
            JSONObject object = JSON.parseObject(jsonStr);

            setType(object.getIntValue("type"));
            setData(object.getString("data"));

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        ParcelUtils.writeToParcel(dest, type);
        ParcelUtils.writeToParcel(dest,data);
    }

    public static final Creator<ChatRoomMessageContent> CREATOR = new Creator<ChatRoomMessageContent>() {

        @Override
        public ChatRoomMessageContent createFromParcel(Parcel source) {
            return new ChatRoomMessageContent(source);
        }

        @Override
        public ChatRoomMessageContent[] newArray(int size) {
            return new ChatRoomMessageContent[size];
        }
    };

    public ChatRoomMessageContent(Parcel parcel){

        type = ParcelUtils.readIntFromParcel(parcel);
        data = ParcelUtils.readFromParcel(parcel);
    }

    @Override
    public int describeContents() {
        return 0;
    }

    public int getType() {
        return type;
    }

    public void setType(int type) {
        this.type = type;
    }

    public String getData() {
        return data;
    }

    public void setData(String data) {
        this.data = data;
    }
}

